package com.example.mingyue.controller;

import com.example.mingyue.common.Result;
import com.example.mingyue.model.dto.UserLoginDto;
import com.example.mingyue.model.entity.User;
import com.example.mingyue.model.vo.UserLoginVO;
import com.example.mingyue.service.UserService;
import com.example.mingyue.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信用户
 * 和普通用户二选一
 */
@RestController
@RequestMapping("/wxUser")
@Slf4j
public class WxUserController {

    @Autowired
    private UserService userService;

    /**
     * 微信用户登录
     * @param userDto
     * @return
     */
    @PostMapping("/login")
    public Result userLogin(@RequestBody UserLoginDto userDto){


        //微信登录
        User user = userService.userLogin(userDto);

        log.info("登录的微信用户{}",user);

        //为微信用户创建Jwt令牌
        //密码通过生成jwt令牌
        Map<String,Object> map = new HashMap<>();
        map.put("id",user.getId());
        String jwt = JwtUtils.generateJwt(map);

        //返沪的VO
        UserLoginVO userLoginVO = new UserLoginVO();
        userLoginVO.setId(user.getId());
        userLoginVO.setOpenId(user.getOpenid());
        userLoginVO.setToken(jwt);

        return Result.success(userLoginVO);
    }
}
